<template>
  <div style="margin-top: 16px; max-width: 1100px; margin-left: auto; margin-right: auto;">
    <div class="breadcrumb-bg">
      <el-breadcrumb separator=">">
        <el-breadcrumb-item>内容管理</el-breadcrumb-item>
        <el-breadcrumb-item>系列课程</el-breadcrumb-item>
        <el-breadcrumb-item><div style="color: black;">{{ isEdit ? '编辑系列课程' : '新增系列课程' }}</div></el-breadcrumb-item>
      </el-breadcrumb>
    </div>
      
    <el-card style="margin-top: 16px; max-width: 1100px; margin-left: auto; margin-right: auto;">
      <div class="header">
        <h2 style="color: #333333; font-size: 16px;width: 140px;">{{ isEdit ? '编辑系列课程' : '新增系列课程' }}</h2>
      </div>
      
      <el-form :model="form" label-width="120px" style="max-width: 900px;">
        <el-form-item label="课程名称" required>
          <el-input v-model="form.name" placeholder="请输入"/>
        </el-form-item>
        <el-form-item label="系列课程图片" required class="upload-form-item">
          <div class="upload-row">
            <el-upload
              class="avatar-uploader big-uploader"
              action=""
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
              :on-change="handleAvatarChange"
              :auto-upload="false"
            >
              <template v-if="form.cover">
                <img :src="form.cover" class="avatar" />
              </template>
              <template v-else>
                <div class="upload-placeholder">
                  <span class="upload-plus">+</span>
                  <span class="upload-text">上传图片</span>
                </div>
              </template>
            </el-upload>
            <div class="upload-desc">
              支持jpg、png等格式文件上传，文件大小不超过10MB，最多可上传1张
            </div>
          </div>
        </el-form-item>
        <el-form-item label="课程介绍">
          <el-input v-model="form.description" type="textarea" :rows="4" placeholder="请输入课程介绍" />
        </el-form-item>
        <el-form-item label="课程状态" required>
          <el-select v-model="form.status" placeholder="请选择课程状态" style="width: 200px;">
            <el-option label="已上架" value="已上架" />
            <el-option label="未上架" value="未上架" />
          </el-select>
        </el-form-item>
        <el-form-item label="课程数量" required>
          <el-input v-model.number="form.courseCount" placeholder="请输入课程数量" style="width: 200px;" />
        </el-form-item>
        <el-form-item label="课时数量" required>
          <el-input v-model.number="form.lessonCount" placeholder="请输入课时数量" style="width: 200px;" />
        </el-form-item>
        <el-form-item label="发布人" required>
          <el-input v-model="form.publisher" placeholder="请输入发布人" style="width: 200px;" />
        </el-form-item>
        <el-form-item label="课程">
          <el-button @click="addSubCourse">+ 添加课程</el-button>
          <el-table :data="form.courses" style="width: 100%; margin-top: 10px;">
            <el-table-column prop="courseName" label="课程信息" width="200"/>
            <el-table-column prop="status" label="状态" width="100"/>
            <el-table-column prop="category" label="课程分类" width="120"/>
            <el-table-column prop="price" label="课程价格（元）" width="120"/>
            <el-table-column prop="lessonCount" label="课时数量" width="100"/>
            <el-table-column prop="updateTime" label="最后更新时间" width="180"/>
            <el-table-column label="操作" width="80">
              <template #default="{ $index }">
                <el-button type="link" @click="removeSubCourse($index)">移除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="课程价格" required>
          <el-radio-group v-model="form.isFree">
            <el-radio :label="false">付费</el-radio>
            <el-radio :label="true">免费</el-radio>
          </el-radio-group>
          <el-input v-if="!form.isFree" v-model.number="form.price" placeholder="商品价格" style="width: 120px; margin-left: 10px;"/> 元
          <el-input v-model.number="form.totalPrice" placeholder="划线价" style="width: 120px; margin-left: 10px;"/> 元
        </el-form-item>
        <el-form-item label="适用范围">
          <el-radio-group v-model="form.publishType">
            <el-radio label="立即上架">立即上架</el-radio>
            <el-radio label="定时上架">定时上架</el-radio>
            <el-radio label="暂不上架">暂不上架</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submit">提交审核</el-button>
          <el-button @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { addSeries, editSeries, getSeriesList } from '../http/series'
import type { Series } from '../type/series'
import { ElMessage } from 'element-plus'

const route = useRoute()
const router = useRouter()
const isEdit = ref(!!route.query.id)
const form = ref<Series>({
  name: '',
  cover: '',
  description: '',
  status: '',
  courseCount: undefined,
  lessonCount: undefined,
  publisher: '',
  price: undefined,
  totalPrice: undefined,
  isFree: false,
  publishType: '立即上架',
  courses: [],
  remark: ''
})

function beforeAvatarUpload(file: File) {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isJPG) {
    ElMessage.error('只能上传 jpg/png 文件!')
    return false
  }
  if (!isLt10M) {
    ElMessage.error('图片大小不能超过 10MB!')
    return false
  }
  return true
}

function handleAvatarChange(file: any) {
  const reader = new FileReader()
  reader.onload = (e: any) => {
    form.value.cover = e.target.result
  }
  reader.readAsDataURL(file.raw)
}

function submit() {
  // 类型转换，确保数字字段为数字
  if (typeof form.value.id === 'string' && form.value.id !== '') {
    form.value.id = Number(form.value.id)
  }
  if (typeof form.value.price === 'string' && form.value.price !== '') {
    form.value.price = Number(form.value.price)
  }
  if (typeof form.value.totalPrice === 'string' && form.value.totalPrice !== '') {
    form.value.totalPrice = Number(form.value.totalPrice)
  }
  if (typeof form.value.courseCount === 'string' && form.value.courseCount !== '') {
    form.value.courseCount = Number(form.value.courseCount)
  }
  if (typeof form.value.lessonCount === 'string' && form.value.lessonCount !== '') {
    form.value.lessonCount = Number(form.value.lessonCount)
  }
  // 确保 courses 字段为数组，且子项的数字字段为数字
  if (form.value.courses && Array.isArray(form.value.courses)) {
    form.value.courses = form.value.courses.map(course => ({
      ...course,
      price: Number(course.price),
      lessonCount: Number(course.lessonCount)
    }))
  }

  // 移除不能提交的字段
  const data = { ...form.value }
  delete data.objectId
  delete data.createdAt
  delete data.updatedAt

  console.log('提交数据', JSON.stringify(data, null, 2));

  if (isEdit.value) {
    editSeries(form.value.objectId!, data).then(() => {
      ElMessage.success('编辑成功')
      router.push('/series')
    }).catch(err => {
      ElMessage.error('编辑失败')
      console.error(err)
    })
  } else {
    addSeries(data).then(() => {
      ElMessage.success('新增成功')
      router.push('/series')
    }).catch(err => {
      ElMessage.error('新增失败')
      console.error(err)
    })
  }
}

function cancel() {
  router.back()
}

onMounted(() => {
  if (isEdit.value) {
    getSeriesList().then(res => {
      const data = res.data.results.find((item: Series) => item.objectId === route.query.id)
      if (data) Object.assign(form.value, data)
    })
  }
  if (!form.value.courses) form.value.courses = [];
})

function addSubCourse() {
  form.value.courses?.push({
    courseName: '',
    status: '已上架',
    category: '',
    price: 0,
    lessonCount: 0,
    updateTime: new Date().toISOString().slice(0, 19).replace('T', ' ')
  })
}

function removeSubCourse(index: number) {
  form.value.courses?.splice(index, 1)
}
</script>

<style scoped>
.el-card {
  border-radius: 12px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.04);
  padding-bottom: 24px;
}

.el-form {
  font-size: 14px;
}
.el-form-item__label {
  color: #333333;
  font-size: 14px;
  font-weight: 500;
}
.el-form-item.is-required .el-form-item__label::before {
  color: #2561EF;
}
.el-input__wrapper,
.el-textarea__inner,
.el-upload {
  border-radius: 6px !important;
  font-size: 14px;
}
.el-input input::placeholder,
.el-textarea__inner::placeholder {
  color: #999999;
  font-size: 13px;
}
.el-upload {
  border-radius: 6px;
}
.avatar {
  border-radius: 6px;
  border: 1px solid #eee;
}
.el-button--primary {
  background: #2561EF;
  border-color: #2561EF;
  color: #fff;
  font-size: 16px;
  border-radius: 6px;
}
.el-button {
  font-size: 16px;
  border-radius: 6px;
}
.el-table {
  border-radius: 12px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.04);
  font-size: 14px;
}
.el-table th {
  background: #f7f8fa;
  color: #333333;
  font-weight: 500;
  font-size: 14px;
}
.el-table td {
  color: #333333;
  font-size: 13px;
}
.el-table__row {
  transition: background 0.2s;
}
.el-table__row:hover {
  background: #f5f7fa;
}
.el-tag.success {
  background: #3DD4A7;
  color: #fff;
  border: none;
}
.tips, .desc, .el-form-item__label {
  color: #999999;
  font-size: 12px;
}
.upload-form-item .el-form-item__label {
  color: #999999;
  font-size: 16px;
  font-weight: 400;
}
.upload-form-item .el-form-item__label::before {
  color: #FA746B !important; /* 必填星号为辅助色 */
}
.upload-row {
  display: flex;
  align-items: center;
}
.big-uploader {
  width: 220px;
  height: 220px;
  background: #fafbfc;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 32px;
  transition: border-color 0.2s;
}
.big-uploader:hover {
  border-color: #2561EF;
}
.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
}
.upload-plus {
  font-size: 36px;
  color: #2561EF;
  font-weight: bold;
  line-height: 1;
}
.upload-text {
  font-size: 16px;
  color: #333333;
  margin-top: 8px;
  font-weight: 500;
}
.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 8px;
}
.upload-desc {
  color: #bbb;
  font-size: 12px;
  margin-left: 12px;
  white-space: nowrap;
}

.breadcrumb-bg {
  background: #f7f8fa;
  padding: 18px 32px 0 32px;
  margin: -32px -32px 0 -32px;
}
.el-breadcrumb {
  font-size: 16px;
  margin-bottom: 8px;
}
.el-breadcrumb__item {
  color: #999999;
}
.el-breadcrumb__item .el-breadcrumb__inner {
  color: #999999;
  font-weight: 400;
}
.el-breadcrumb__item:last-child .el-breadcrumb__inner {
  color: #333333 !important;
  font-weight: 500;
}
.el-breadcrumb__separator {
  color: #999999 !important;
}
.header::before {
  content: '';
  display: inline-block;
  width: 6px;
  height: 19px;
  background: #2561EF;
  border-radius: 4px;
  margin-right:10px;
}

.header::after {
  content: '';
  display: inline-block;
  width: 100%;
  height: 0.5px;
  background: #CCCCCC;
  border-radius: 4px;
  margin-right:10px;
 
}

.header {
  display: flex;
  align-items: center;
  margin-bottom: 18px;
}
.header h2 {
  font-size: 18px;
  font-weight: 500;
  color: #2561EF;
}

</style>